package com.bieber.smartpost.invoke.filter;

import com.bieber.smartpost.invoke.FilterChain;
import com.bieber.smartpost.model.RequestEntity;
import com.jbeer.framework.annotation.Bean;

/**
 * Created by bieber on 14-11-30.
 */
@Bean
public class LocalhostUrlFilter extends AbstractFilter {

    private static final  String HTTP_LOCALHOST_TOKEN = "http://localhost";

    private static final String HTTPS_LOCALHOST_TOKEN = "https://localhost";

    public void doFilter(FilterChain chain, RequestEntity entity) {
        String url = entity.getUrl();
        String tempURL = url.toLowerCase();
        StringBuffer targetURL = new StringBuffer();
        if(tempURL.indexOf(HTTP_LOCALHOST_TOKEN)==0){
            targetURL.append("http://").append(entity.getClientIp()).append(url.substring(HTTP_LOCALHOST_TOKEN.length()));
            url = targetURL.toString();
        }else if(tempURL.indexOf(HTTPS_LOCALHOST_TOKEN)==0){
            targetURL.append("https://").append(entity.getClientIp()).append(url.substring(HTTPS_LOCALHOST_TOKEN.length()));
            url = targetURL.toString();
        }
        entity.setUrl(url);
        chain.doChain(entity);
    }

    public int order() {
        return Integer.MAX_VALUE-1;
    }

}
